package com.study.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.ZooKeeper;

/**
 * zkpath 提供简单的API来构建ZNode路径，递归创建和删除节点
 */
public class ZkPathCurator {

    private static String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
    private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    private static String path= "/zlx";
    private static CuratorFramework client = CuratorFrameworkFactory
            .builder()
            .connectString(connectStr)
            .sessionTimeoutMs(5000)
            .retryPolicy(retryPolicy)
            //指定命名空间
            // .namespace("")
            .build();

    public static void main(String[] args) throws Exception {
        client.start();
        ZooKeeper zooKeeper = client.getZookeeperClient().getZooKeeper();
        System.out.println(ZKPaths.fixForNamespace(path, "/sub"));
        System.out.println(ZKPaths.makePath(path, "/sub"));
        System.out.println(ZKPaths.getNodeFromPath("/zlx/sub1"));
        ZKPaths.PathAndNode pn = ZKPaths.getPathAndNode("/zlx/sub1");
        System.out.println(pn.getPath());
        System.out.println(pn.getNode());
        ZKPaths.mkdirs(zooKeeper, path + "/child1");
        ZKPaths.mkdirs(zooKeeper, path + "/child2");
        System.out.println(ZKPaths.getSortedChildren(zooKeeper, path));
        ZKPaths.deleteChildren(zooKeeper, path, true);
    }
}
